package com.three.common.message.base;

import com.google.protobuf.InvalidProtocolBufferException;
import com.three.api.connection.Connection;
import com.three.api.protocol.Packet;
import com.three.protocol.BaseModule;
import com.three.protocol.CommandEnum;
import com.three.tools.Utils;
import com.three.utils.StringUtils;

import java.util.Arrays;
import java.util.Map;

/**
 * Created by mathua on 2017/5/28.
 */
public final class HttpRequestMessage extends BaseMessage {
    private byte method;
    private String uri;
    private Map<String, String> headers;
    private byte[] body;

    public HttpRequestMessage(Connection connection) {
        super(new Packet(CommandEnum.Command.HTTP_PROXY, genSessionId()), connection);
    }

    public HttpRequestMessage(Packet message, Connection connection) {
        super(message, connection);
    }

    @Override
    public void decode(byte[] body) throws InvalidProtocolBufferException {
        BaseModule.HttpRequest_10 bodyData = BaseModule.HttpRequest_10.parseFrom(body);
        method = (byte) bodyData.getMethod().getNumber();
        uri = bodyData.getUri();
        headers = Utils.headerFromString(bodyData.getHeaders());
        this.body = StringUtils.praseFromString(bodyData.getBody());
    }

    @Override
    public byte[] encode() {
        BaseModule.HttpRequest_10.Builder builder = BaseModule.HttpRequest_10.newBuilder();
        builder.setMethod(BaseModule.MethodType.valueOf(method));
        builder.setUri(uri);
        builder.setHeaders(Utils.headerToString(headers));
        builder.setBody(Arrays.toString(body));
        return builder.build().toByteArray();
    }

    public String getMethod() {
        switch (method) {
            case 0:
                return "GET";
            case 1:
                return "POST";
            case 2:
                return "PUT";
            case 3:
                return "DELETE";
        }
        return "GET";
    }

    @Override
    public String toString() {
        return "HttpRequestMessage{" +
                "method=" + method +
                ", uri='" + uri + '\'' +
                ", headers=" + headers +
                ", body=" + (body == null ? "" : body.length) +
                '}';
    }

    public String getUri() {
        return uri;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public byte[] getBody() {
        return body;
    }
}
